package mongo

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/cgs/app/models"
	v1 "cgs-server/server/cgs/app/models/v1"
	"cgs-server/server/cgs/app/models/vo"
	"cgs-server/server/cgs/app/store"
	"cgs-server/server/model"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
)

type worksheetPrint struct {
	db             *helper.Mongo
	collectionName string
}

func (w *worksheetPrint) Save(wg *models.WorksheetPrint, user *model.User, opts v1.CreateOptions) error {
	wg.ResolveEntity(wg, user)
	_, err := w.db.InsertOne(w.collectionName, wg)
	return err
}

func (w *worksheetPrint) Get(wg *models.WorksheetPrint, user *model.User, opts v1.GetOptions) (*vo.WorksheetPrint, error) {
	filter := bson.M{}
	if !wg.Id.IsZero() {
		filter["id"] = wg.Id
	}
	//if wg.AppId != "" {
	//	filter["appId"] = wg.AppId
	//}
	wg.ResolveFilter(wg, user, &filter)
	result := &vo.WorksheetPrint{}
	find, err := w.db.FindOne(w.collectionName, filter, result)
	if !find {
		return nil, fmt.Errorf("worksheet group not found: %s", wg.GetId())
	}
	return result, err
}

func (w *worksheetPrint) Update(wg *models.WorksheetPrint, user *model.User, opts v1.UpdateOptions) error {
	filter := bson.M{}
	if !wg.Id.IsZero() {
		filter["id"] = wg.Id
	} else {
		return fmt.Errorf("id is required")
	}
	wg.ResolveFilter(wg, user, &filter)
	set := bson.M{}
	if wg.Name != "" {
		set["name"] = wg.Name
	}
	if wg.Path != "" {
		set["path"] = wg.Path
	}
	wg.ResolveUpdateCondition(wg, user, &set)
	update := bson.M{
		"$set": set,
	}
	_, err := w.db.UpdateOne(w.collectionName, filter, update)
	return err
}

func (w *worksheetPrint) Delete(wg *models.WorksheetPrint, user *model.User, opts v1.DeleteOptions) error {
	filter := bson.M{}
	if !wg.Id.IsZero() {
		filter["id"] = wg.Id
	}
	wg.ResolveFilter(wg, user, &filter)
	_, err := w.db.DeleteOne(w.collectionName, filter)
	return err
}

func (w *worksheetPrint) List(wg *models.WorksheetPrint, user *model.User, opts v1.ListOptions) (*vo.WorksheetPrintList, error) {
	filter := opts.GetFilter()
	wg.ResolveFilter(wg, user, &filter)
	results := &vo.WorksheetPrintList{}
	err := w.db.FindMany(w.collectionName, filter, results, opts.ResolveFindOptions())
	return results, err
}

func newWorksheetPrintStore(d *datastore) store.WorksheetPrintStore {
	return &worksheetPrint{
		db:             d.db,
		collectionName: server.WorksheetPrintCollectionName,
	}
}
